<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 会员卡接口
 */
namespace app\allwin\controller\api\v4;
use app\allwin\controller\api\Base;
use app\allwin\model\Card as ModelCard;
use app\allwin\model\Coupon;
use app\allwin\model\Card as AllwinCard;
use app\allwin\model\CardUser;
use app\allwin\model\CardUserOrder;
use app\common\facade\WechatPay;

class Card extends Base{

    /**
     * 初始化当前应用管理员是不是联盟城市账户
     * @return void
     */
    public function initialize() {
        parent::initialize();
    }

    /**
     * 判断好店是否有储值卡
     */
    public function isCard(){ 
        $param['store_id'] = $this->request->param('store_id/d',0);
        $param['signkey']  = $this->request->param('signkey');
        $param['sign']     = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson(403,'签名失败');
        }
        $card = ModelCard::where(['member_miniapp_id' => $this->miniapp_id,'store_id' => $param['store_id'],'is_lock' => 0])->count();
        return enjson(200,'成功',$card);
    }

    /**
     * 判断好店是否有储值卡
     */
    public function storeCard(int $store_id){ 
        $param['store_id'] = $this->request->param('store_id/d',0);
        $param['signkey']  = $this->request->param('signkey');
        $param['sign']     = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson(403,'签名失败');
        }
        $card = ModelCard::where(['member_miniapp_id' => $this->miniapp_id,'store_id' => $param['store_id'],'is_lock' => 0])->field('id,coupon_id,price,name,tips,coupon_num')->select();
        if ($card->isEmpty()) {
            return enjson(404,'好店未开通活动');
        }
        $user_card = CardUser::where(['store_id' => $param['store_id'],'user_id' => $this->user->id])->column('card_id');
        $data = [];
        foreach ($card as $key => $value) {
            $data[$key] = $value;
            $data[$key]['tips']   = str_replace('<img', '<img class="img" style="max-width:100%;height:auto"',dehtml($value['tips']));;
            $data[$key]['oncard'] = in_array($value['id'],$user_card) ? 1: 0;
        }
        $idArr = array_column($data,'oncard');
        array_multisort($idArr,SORT_ASC,$data);
        return enjson(200,'成功',$data);
    }

    /**
     * 读取活动优惠券
    */
    public function getCoupon(){
        $param['card_id'] = $this->request->param('card_id/d');
        $param['page']    = $this->request->param('page/d',1);
        $param['signkey'] = $this->request->param('signkey');
        $param['sign']    = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson($rel['code'],'签名验证失败');
        }
        $card = ModelCard::where(['id' => $param['card_id']])->field('coupon_ids')->find();
        if (empty($card)) {
            return enjson(204,'没有优惠券');
        }
        $condition[] = ['id','in',$card->coupon_ids];
        $condition[] = ['is_lock','=',0];
        $condition[] = ['is_platform','=',0];
        $condition[] = ['is_end','=',0];
        $condition[] = ['num','>',0];
        $condition[] = ['endtime','>',time()];
        $coupon = Coupon::where($condition)->field('id,name,size,tips,discount,price,types')->order('is_top desc,sort desc,size desc')->paginate(6);
        if ($coupon->isEmpty()) {
            return enjson(204,'没有优惠券');
        }
        $data = [];
        foreach ($coupon as $key => $value) {
            $data[$key]['id']        = $value['id'];
            $data[$key]['name']      = $value['name'];
            $data[$key]['size']      = round($value['size']);
            $data[$key]['tips']      = $value['tips'];
            $data[$key]['types']     = $value['types'];
            $data[$key]['price']     = $value['types'] ? $value['discount'].'折':$value['price'];
        }
        return enjson(200,'成功',$data);
    } 

    /**
     * 开通商家会员卡
     * @param string $no
     * @return void
     */
    public function payment(){
        $param = [
            'card_id'    => $this->request->param('card_id/d'),
            'store_id'   => $this->request->param('store_id/d'),
            'coupon_ids' => $this->request->param('coupon_ids/s','[]'),
            'signkey'    => $this->request->param('signkey'),
            'sign'       => $this->request->param('sign'),
        ];       
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson(403,$rel['msg']);
        }
        $param['id']                = $param['card_id'];
        $param['member_miniapp_id'] = $this->miniapp_id;
        $validate = $this->validate($param,'Card.regcard');
        if (true !== $validate) {
            return enjson(403,$validate);
        }
        $card = AllwinCard::where(['id' => $param['card_id'],'store_id' => $param['store_id'],'is_lock' => 0])->find();
        if(empty($card)){
            return enjson(403,'未找到活动信息');
        }
        $is_card = CardUser::where(['member_miniapp_id' => $this->miniapp_id,'card_id' => $param['id'],'user_id' => $this->user->id])->find();
        if($is_card){
            return enjson(403,'您已参加过当前活动');
        }
        //判断并读取邀请用户的所属店铺ID
        $order_no   = $this->user->invite_code.order_no();
        $coupon_ids = ids(json_decode($param['coupon_ids']),true);
        //读取并判断是否VIP
        $card_data                      = [];
        $card_data['member_miniapp_id'] = $card->member_miniapp_id;
        $card_data['store_id']          = $card->store_id;
        $card_data['card_id']           = $card->id;
        $card_data['user_id']           = $this->user->id;
        $card_data['coupon_id']         = $card->coupon_id;
        $card_data['coupon_ids']        = empty($coupon_ids)?'[]':json_encode($coupon_ids);
        $card_data['user_card_id']      = 0;
        $card_data['state']             = 0;
        $card_data['amount']            = $card->price;
        $card_data['order_no']          = $order_no;
        $card_data['create_time']       = time();
        $rel = CardUserOrder::create($card_data);
        if(empty($rel)){
            return enjson(403,'活动订单创建失败,请稍后再试');
        }
        $payparm = [
            'openid'       => $this->user->miniapp_uid,
            'miniapp_id'   => $this->miniapp_id,
            'name'         => $card->store->name.'储值活动',
            'order_no'     => $order_no,
            'total_fee'    => $card->price*100,
            'notify_url'   => api(4,'allwin/cardnotify/index',$this->miniapp_id),
        ];
        //读取配置
        $setting = model('AllwinConfig')->getConfig($this->miniapp_id);
        if($setting->is_psp == 1){ //服务商模式
            if($card->store->mch_id){
                $default_mchid = model('MchId')->getMch($card->store->mch_id);  //商户的商户号
            }else{
                $default_mchid = model('MchId')->getMch(0,$this->miniapp_id);  //默认收款账户
            }
            if (empty($default_mchid)) {
                return enjson(403,'未找到商户号');
            }
            $payparm['mchid']          = $default_mchid->mchid;  
            $payparm['profit_sharing'] = 'N';
        }
        $ispay = WechatPay::orderPay($payparm);
        if($ispay['code'] == 0){
            return enjson(403,$ispay['msg']);
        }
        return enjson(200,'成功',$ispay['data']);
    }

    /**
     * 查看用户所有储值卡
     * @return void
     */
    public function userCard(){
        $param = [
            'page'       => $this->request->param('page/d',1),
            'signkey'    => $this->request->param('signkey'),
            'sign'       => $this->request->param('sign'),
        ];       
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson(403,$rel['msg']);
        }
        //判断数量
        $card = CardUser::where(['user_id' => $this->user->id,'member_miniapp_id' => $this->miniapp_id])->paginate(10,true);
        if ($card->isEmpty()) {
            return json(['code'=>204,'msg'=>'没有储值卡']);
        }
        $data = [];
        foreach ($card as $key => $value) {
            if(!empty($value->couponUser->id)){
                $data[$key]['id']                  = $value->id;
                $data[$key]['store_id']            = $value->store_id;
                $data[$key]['amount']              = $value->amount;
                $data[$key]['create_time']         = date('Y-m-d H:i:s',$value->create_time);
                $data[$key]['store_name']          = $value->store->name;
                $data[$key]['address']             = $value->store->address;
                $data[$key]['name']                = $value->card->name;
                $data[$key]['coupon']['id']        = $value->couponUser->id;
                $data[$key]['coupon']['coupon_id'] = $value->couponUser->coupon_id;
                $data[$key]['coupon']['name']      = $value->couponUser->name;
                $data[$key]['coupon']['price']     = $value->couponUser->types ? $value->couponUser->discount.'折':$value->couponUser->price;
                $data[$key]['coupon']['tips']      = $value->couponUser->tips;
                $data[$key]['coupon']['user_size'] = round($value->couponUser->user_size);
                $data[$key]['coupon']['types']     = $value->couponUser->types;
                $data[$key]['tips']             = $value->card->tips;
            }
        } 
        return json(['code'=>200,'msg'=>"成功",'data' => $data]);
    }

}